<?php

namespace User\Controller;

use Think\Page;
use User\Model\FactoryModel;
use User\Model\QuestionnaireModel;

class QuestionnaireController extends UserController
{
    public function __construct()
    {
        parent::__construct();
        if (!headers_sent() && // 如果页面头部信息还没有输出
            extension_loaded("zlib") && // 而且php已经加载了zlib扩展
            strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")
        ) //而且浏览器接受GZIP
        {
            ini_set('zlib.output_compression', 'On');
            ini_set('zlib.output_compression_level', '4');
        }
    }

    public function index()
    {
        $condition['status'] = array("NEQ", QuestionnaireModel::QUESTIONNAIRE_DELETE);
        $condition['token'] = $this->wxuser['token'];
        $title = I("get.title", "", "");
        if (!empty($title)) {
            $condition['title'] = array('LIKE', "%" . $title . "%");
            $this->assign("title", $title);
        }
        $count = M("questionnaire")->where($condition)->count();

        $page = new Page($count, 15);
        $show = $page->show();
        $this->assign("page", $show);

        $list = M("questionnaire")->where($condition)->limit($page->firstRow . ',' . $page->listRows)->order('id desc')->field('id,title,title_image,status,createdate')->select();
        if (!empty($list)) {
            foreach ($list as &$value) {
                $value['link'] = "http://" . $_SERVER['SERVER_NAME'] . "/Wap/Questionnaire/index?id=" . $value['id'];
            }
        }
        $this->assign("list", $list);
        $this->display();
    }

    public function edit()
    {
        $id = I("get.id", -1, "");
        $condition['id'] = $id;
        $condition['token'] = $this->wxuser['token'];
        $questionnaire = M("questionnaire")->where($condition)->find();
        $questionnaire['background_music'] = $questionnaire['background_music'] ? $questionnaire['background_music'] :
            '/Public/audio/questionnaire/background_music.mp3';
        $this->assign("questionnaire", $questionnaire);
        $this->display();
    }

    public function update()
    {
        $id = I("post.id", -1, "");
        $data = array(
            'token' => $this->wxuser['token'],
            'title' => I("post.title", "", ""),
            'startdate' => I("post.startdate", "", ""),
            'enddate' => I("post.enddate", "", ""),
            'keyword' => I("post.keyword", "", ""),
            'push_desc' => I("post.push_desc", "", ""),
            'share_title' => I("post.share_title", "", ""),
            'share_desc' => I("post.share_desc", "", ""),
            'share_link' => I("post.share_link", "", ""),
            'title_image' => I("post.title_image", "", "") ? I("post.title_image", "", "") : '/Public/images/questionnaire/title_image.jpg',
            'background_image' => I("post.background_image", "", "") ? I("post.background_image", "", "") : '/Public/images/questionnaire/background.jpg',
            'button_image' => I("post.button_image", "", ""),
            'theme_color' => I("post.theme_color", 1, ""),
            'background_music' => I("post.background_music", "", ""),
//            'music_image' => I( "post.music_image", "", "" ),
            'push_image' => I("post.push_image", "", ""),
            'share_image' => I("post.share_image", "", "") ? I("post.share_image", "", "") : '/Public/images/questionnaire/share_image.jpg',
            'need_register' => I("post.need_register", "", "") ? I("post.need_register", "", "") : 0,
            'reserve' => I("post.reserve", "", "") ? I("post.reserve", "", "") : 0,
            'need_music' => I("post.need_music", QuestionnaireModel::MUSIC_ON, "")
        );
        if (I("post.need_music", QuestionnaireModel::MUSIC_ON, "") == QuestionnaireModel::MUSIC_OFF) {
            $data["background_music"] = "";
        }
        if (trim(I("post.rules", "", "")) == '<p><br></p>') {
            $data['rules'] = '';
        } else {
            $data['rules'] = trim(I("post.rules", "", ""));
        }
        $questionnaire = M("questionnaire");
        $result = null;
        if ($id != -1 && !empty($id)) {
            $data['id'] = $id;
            $result['updated'] = $questionnaire->save($data);
            $result['success'] = $result['updated'];
        } else {
            $data['id'] = $questionnaire->add($data);
            $result['id'] = $data['id'];
            $result['added'] = $data['id'] ? true : false;
            $result['success'] = $result['added'];
        }
        if ($data['keyword'] != '' && $result['success']) {
            $deleted = M("keyword")->where(array("token" => $this->wxuser['token'], 'pid' => $data['id'], 'module' => 'Questionnaire'))->delete();
            $keywords = explode(",", $data['keyword']);
            if ($deleted !== false) {
                foreach ($keywords as $keyword) {
                    $added = M("keyword")->add(array("keyword" => $keyword, "pid" => $data['id'], "token" => $this->wxuser['token'], "module" => "Questionnaire"));
                    if (!$added) {
                        $result['success'] = false;
                    }
                }
            } else if ($deleted === false) {
                $result['success'] = false;
            }
        }
        if ($result['success'] > 0 || ($result['success'] === 0 && $data['id'] > 0)) {
            $this->success("保存成功", "/User/Questionnaire/index");
        } else {
            $this->error("保存失败", "/User/Questionnaire/index");
        }
    }

    public function statusQuestionnaire()
    {
        $status = I("get.status", "", "");
        $condition['id'] = I("get.id", "", "");
        $condition['token'] = $this->wxuser['token'];
        if ($status == "active") {
            $updated = M("questionnaire")->where($condition)->save(array("status" => QuestionnaireModel::QUESTIONNAIRE_ACTIVE));
            $message = "发布成功";
        } elseif ($status == "pending") {
            $updated = M("questionnaire")->where($condition)->save(array("status" => QuestionnaireModel::QUESTIONNAIRE_PENDING));
            $message = "停用成功";
        } else {
            $updated = M("questionnaire")->where($condition)->save(array("status" => QuestionnaireModel::QUESTIONNAIRE_DELETE));
            $message = "删除成功";
        }
//        if( $updated ){
        $this->success($message, "", true);
//        }else{
//            $this->error( "操作失败", "", true);
//        }
    }

    public function question()
    {
        $questionnaire_id = I("get.id", -1, "");
        $where["id"] = $questionnaire_id;
        $questionnaire = M("questionnaire")->where($where)->find();
        $random1 = unserialize($questionnaire['random_condition1']);
        $random2 = unserialize($questionnaire['random_condition2']);
        $random3 = unserialize($questionnaire['random_condition3']);
        $random_list = array();
        if (!empty($random2)) {
            $random_list[] = $random2;
        }
        if (!empty($random3)) {
            $random_list[] = $random3;
        }
        $condition['questionnaire_id'] = $questionnaire_id;
        $condition['status'] = array("NEQ", QuestionnaireModel::QUESTION_DELETE);
        $condition["type"] = array("NEQ", QuestionnaireModel::TYPE_BRANCH);
        $count = M("questionnaire_questions")->where($condition)->count();

        $page = new Page($count, 15);
        $show = $page->show();
        $this->assign("page", $show);

//        $list = M("questionnaire_questions")->where($condition)->limit($page->firstRow . ',' . $page->listRows)
//            ->order('displayorder asc')->select();
        $list = M("questionnaire_questions")->where($condition)->order('displayorder asc')->select();
        $this->assign("list", $list);
        $this->assign("questionnaire_id", $questionnaire_id);
        $this->assign("questionnaire", $questionnaire);
        $this->assign("random1", $random1);
        $this->assign("random_list", $random_list);
        $this->display();
    }

    public function deleteQuestions()
    {
        $ids = I("get.ids", "", "");
        if (!empty($ids)) {
            $ids = explode('|', $ids);
        }
        $condition['id'] = array('IN', $ids);
        $updated = M("questionnaire_questions")->where($condition)->save(array('status' => QuestionnaireModel::QUESTION_DELETE));
        if ($updated) {
            $this->success("删除成功", "", true);
        } else {
            $this->error("删除失败", "", true);
        }
    }

    public function deleteQuestion()
    {
        $condition['id'] = I("get.id", "", "");
        $updated = M("questionnaire_questions")->where($condition)->save(array('status' => QuestionnaireModel::QUESTION_DELETE));
        if ($updated) {
            $this->success("删除成功", "", true);
        } else {
            $this->error("删除失败", "", true);
        }
    }

    public function editQuestion()
    {
        $question_id = I("get.question_id", -1, "");
        $questionnaire_id = I("get.questionnaire_id", -1, "");
        $where_question["id"] = $question_id;
        $question = M("questionnaire_questions")->where($where_question)->find();
        $where_options["question_id"] = $question_id;
        $where_options["status"] = QuestionnaireModel::ANSWER_ACTIVE;
        $question_options = M("questionnaire_questions_options")->where($where_options)->select();
        //所有分支题目
        $where_branch["questionnaire_id"] = $questionnaire_id;
        $where_branch["status"] = QuestionnaireModel::QUESTION_ACTIVE;
        $where_branch["type"] = QuestionnaireModel::TYPE_BRANCH;
        $branch_questions = M("questionnaire_questions")->where($where_branch)->order("displayorder asc")->select();
        $this->assign("branch_questions", $branch_questions);
        $this->assign("question", $question);
        $this->assign("question_options", $question_options);
        $this->assign("questionnaire_id", $questionnaire_id);
        $this->display();
    }

    public function updateQuestion()
    {
        $id = I("post.id", -1, "");
        $questionnaire_id = I("post.questionnaire_id", -1, "");
        $where_last["questionnaire_id"] = $questionnaire_id;
        $where_last["status"] = QuestionnaireModel::QUESTION_ACTIVE;
        $where_last["type"] = QuestionnaireModel::TYPE_MAIN;
        $last = M("questionnaire_questions")->where($where_last)->order("displayorder desc")->getField("displayorder");
        $question_data = array(
            'questionnaire_id' => $questionnaire_id,
            'title' => I("post.question_title", "", ""),
            'is_single' => I("post.is_single", 1, "")
        );
        $optionid = I("post.optionid", "", "");
        $title = I("post.title", "", "");
        $title_image = I("post.title_image", "", "");
        $score = I("post.score", "", "");
        $correct_option = I("post.correct_option", "", "");
        $result = $added_id = $update_id = false;
        if ($id != -1 && !empty($id)) {
            $question_id = $question_data['id'] = $id;
            $update_id = M("questionnaire_questions")->save($question_data);
        } else {
            $question_data['displayorder'] = intval($last) + 1;
            $added_id = $question_id = M("questionnaire_questions")->add($question_data);
        }
        if (!empty($optionid)) {
            foreach ($optionid as $key => $value) {
                $answer_none = 0;
                foreach ($correct_option as $key2 => $value2) {
                    if ($value2 == QuestionnaireModel::ANSWER_ACTIVE) {
                        $answer_none = QuestionnaireModel::ANSWER_ACTIVE;
                    }
                }
                if ($value != 0) {
                    $question_option_data = array(
                        'id' => $optionid[$key],
                        'question_id' => $question_id,
                        'title' => $title[$key],
                        'title_image' => $title_image[$key],
                        'score' => $score[$key],
                        'correct_answer' => ($answer_none == QuestionnaireModel::ANSWER_ACTIVE) ?
                            ($correct_option[$key] == QuestionnaireModel::ANSWER_ACTIVE ?
                                QuestionnaireModel::ANSWER_ACTIVE : QuestionnaireModel::ANSWER_DELETE) :
                            QuestionnaireModel::ANSWER_NONE
                    );
                    $result = M("questionnaire_questions_options")->save($question_option_data);
                } else {
                    $question_option_data = array(
                        'question_id' => $question_id,
                        'title' => $title[$key],
                        'title_image' => $title_image[$key],
                        'score' => $score[$key],
                        'correct_answer' => ($answer_none == QuestionnaireModel::ANSWER_ACTIVE) ?
                            ($correct_option[$key] == QuestionnaireModel::ANSWER_ACTIVE ?
                                QuestionnaireModel::ANSWER_ACTIVE : QuestionnaireModel::ANSWER_DELETE) :
                            QuestionnaireModel::ANSWER_NONE
                    );
                    M("questionnaire_questions_options")->add($question_option_data);
                }

            }
            if ($result !== false) {
                $this->success("保存成功", "/User/Questionnaire/question?id=" . $questionnaire_id);
            } else {
                $this->error("保存失败", "/User/Questionnaire/question?id=" . $questionnaire_id);
            }
        } else {
            if ($added_id !== false || $update_id !== false) {
                $this->success("保存成功", "/User/Questionnaire/question?id=" . $questionnaire_id);
            } else {
                $this->error("保存失败", "/User/Questionnaire/question?id=" . $questionnaire_id);
            }
        }
    }

    public function addOption()
    {
        $questionnaire_id = I("get.questionnaire_id", -1, "");
        $question_id = I("get.question_id", -1, "");
        $question_title = I("get.question_title", "", "");
        $type = I("get.type", QuestionnaireModel::TYPE_MAIN, "");
        $is_extra = I("get.is_extra", QuestionnaireModel::EXTRA_OFF);
        $where['id'] = $question_id;
        $question = M("questionnaire_questions")->where($where)->find();
        if (!empty($question)) {
            $data_option = array(
                "question_id" => $question_id,
                "status" => QuestionnaireModel::ANSWER_ACTIVE,
                "is_extra" => $is_extra
            );
            $added_id = M("questionnaire_questions_options")->add($data_option);
            if ($added_id !== false) {
                $this->ajaxReturn(array('status' => 1, 'question_id' => $question_id, "option_id" => $added_id));
            } else {
                $this->ajaxReturn(array('status' => 0, 'info' => '增加失败'));
            }
        } else {
            $data_question = array(
                "questionnaire_id" => $questionnaire_id,
                "title" => $question_title,
                "status" => QuestionnaireModel::QUESTION_ACTIVE,
                "type" => $type
            );
            $where_last["questionnaire_id"] = $questionnaire_id;
            $where_last["status"] = QuestionnaireModel::QUESTION_ACTIVE;
            $where_last["type"] = $type;
            $last = M("questionnaire_questions")->where($where_last)->order("displayorder desc")
                ->getField("displayorder");
            $data_question["displayorder"] = intval($last) + 1;
            $question_id = M("questionnaire_questions")->add($data_question);
            if ($question_id !== false) {
                $data_option = array(
                    "question_id" => $question_id,
                    "status" => QuestionnaireModel::ANSWER_ACTIVE,
                    "is_extra" => $is_extra
                );
                $added_id = M("questionnaire_questions_options")->add($data_option);
                if ($added_id !== false) {
                    $this->ajaxReturn(array('status' => 1, 'question_id' => $question_id, "option_id" => $added_id));
                } else {
                    $this->ajaxReturn(array('status' => 0, 'info' => '增加失败'));
                }
            } else {
                $this->ajaxReturn(array('status' => 0, 'info' => '增加失败'));
            }
        }
    }

    public function deleteOption()
    {
        $where['id'] = I("get.id", -1, "");
        $updated = M("questionnaire_questions_options")->where($where)
            ->save(array('status' => QuestionnaireModel::ANSWER_DELETE));
        if ($updated) {
            $this->success("删除成功", "", true);
        } else {
            $this->error("删除失败", "", true);
        }
    }

    public function branchQuestion()
    {
        $questionnaire_id = I("get.id", -1, "");
        $where["id"] = $questionnaire_id;
        $questionnaire = M("questionnaire")->where($where)->find();
        $condition['questionnaire_id'] = $questionnaire_id;
        $condition['status'] = array("NEQ", QuestionnaireModel::QUESTION_DELETE);
        $condition["type"] = array("EQ", QuestionnaireModel::TYPE_BRANCH);
        $count = M("questionnaire_questions")->where($condition)->count();

        $page = new Page($count, 15);
        $show = $page->show();
        $this->assign("page", $show);

        $list = M("questionnaire_questions")->where($condition)->limit($page->firstRow . ',' . $page->listRows)
            ->order('displayorder asc')->select();
        $this->assign("list", $list);
        $this->assign("questionnaire_id", $questionnaire_id);
        $this->assign("questionnaire", $questionnaire);
        $this->display();
    }

    public function editBranchQuestion()
    {
        $question_id = I("get.question_id", -1, "");
        $questionnaire_id = I("get.questionnaire_id", -1, "");
        $where_question["id"] = $question_id;
        $question = M("questionnaire_questions")->where($where_question)->find();
        $where_options["question_id"] = $question_id;
        $where_options["status"] = QuestionnaireModel::ANSWER_ACTIVE;
        $question_options = M("questionnaire_questions_options")->where($where_options)->select();
        $this->assign("question", $question);
        $this->assign("question_options", $question_options);
        $this->assign("questionnaire_id", $questionnaire_id);
        $this->display();
    }

    public function updateBranchQuestion()
    {
        $id = I("post.id", -1, "");
        $questionnaire_id = I("post.questionnaire_id", -1, "");
        $where_last["questionnaire_id"] = $questionnaire_id;
        $where_last["status"] = QuestionnaireModel::QUESTION_ACTIVE;
        $where_last["type"] = QuestionnaireModel::TYPE_BRANCH;
        $last = M("questionnaire_questions")->where($where_last)->order("displayorder desc")->getField("displayorder");
        $question_data = array(
            'questionnaire_id' => $questionnaire_id,
            'title' => I("post.question_title", "", ""),
            'type' => QuestionnaireModel::TYPE_BRANCH,
            'is_single' => I("post.is_single", 1, "")
        );
        $optionid = I("post.optionid", "", "");
        $title = I("post.title", "", "");
        $title_image = I("post.title_image", "", "");
        $score = I("post.score", "", "");
        $correct_option = I("post.correct_option", "", "");
        $result = $added_id = $update_id = false;
        if ($id != -1 && !empty($id)) {
            $question_id = $question_data['id'] = $id;
            $update_id = M("questionnaire_questions")->save($question_data);
        } else {
            $question_data['displayorder'] = intval($last) + 1;
            $added_id = $question_id = M("questionnaire_questions")->add($question_data);
        }
        if (!empty($optionid)) {
            foreach ($optionid as $key => $value) {
                $answer_none = 0;
                foreach ($correct_option as $key2 => $value2) {
                    if ($value2 == QuestionnaireModel::ANSWER_ACTIVE) {
                        $answer_none = QuestionnaireModel::ANSWER_ACTIVE;
                    }
                }
                $question_option_data = array(
                    'id' => $optionid[$key],
                    'question_id' => $question_id,
                    'title' => $title[$key],
                    'title_image' => $title_image[$key],
                    'score' => $score[$key],
                    'correct_answer' => ($answer_none == QuestionnaireModel::ANSWER_ACTIVE) ? $correct_option[$key] :
                        QuestionnaireModel::ANSWER_NONE
                );
                $result = M("questionnaire_questions_options")->save($question_option_data);
            }
            if ($result !== false) {
                $this->success("保存成功", "/User/Questionnaire/branchQuestion?id=" . $questionnaire_id);
            } else {
                $this->error("保存失败", "/User/Questionnaire/branchQuestion?id=" . $questionnaire_id);
            }
        } else {
            if ($added_id !== false || $update_id !== false) {
                $this->success("保存成功", "/User/Questionnaire/branchQuestion?id=" . $questionnaire_id);
            } else {
                $this->error("保存失败", "/User/Questionnaire/branchQuestion?id=" . $questionnaire_id);
            }
        }
    }

    public function branchOptions()
    {
        $option_id = I("get.option_id", -1, "");
        $where["id"] = $option_id;
        $questionnaire_questions_options = M("questionnaire_questions_options")->where($where)->find();
        $branch_list = array();
        if (!empty($questionnaire_questions_options["reserve"])) {
            $branch_list = explode(",", $questionnaire_questions_options["reserve"]);
        }
        $this->ajaxReturn(array('status' => 1, 'branch_list' => $branch_list));
    }

    public function updateBranchs()
    {
        $ids = I("get.ids", "", "");
        $question_option_id = I("get.question_option_id", -1, "");
        $where["id"] = $question_option_id;
        if (!empty($ids)) {
            $updated = M("questionnaire_questions_options")->where($where)->save(array("reserve" => $ids));
        } else {
            $updated = M("questionnaire_questions_options")->where($where)->save(array("reserve" => ""));
        }
        if ($updated !== false) {
            $this->ajaxReturn(array('status' => 1, 'info' => "保存分支题目成功"));
        } else {
            $this->ajaxReturn(array('status' => 0, 'info' => "保存分支题目失败"));
        }
    }

    public function uploadFile()
    {
        $img = I("post.img", "", "");
        $type = I("post.type", "image", "");
        if ($type == "image") {
            $ret = FactoryModel::ajaxImgUpload($img, 'questionnaire');
        } else {
            $ret = array('msg' => "上传失败", 'code' => '-1');
            if (empty($img)) {
                $res['msg'] = '无文件信息';
                return $res;
            }
            list($type, $data) = explode(',', $img);
            $ext = '.mp3';
            $dir = "Public/Uploads/questionnaire/" . date('Ymd');
            if (!is_dir($dir)) mkdir($dir); // 如果不存在则创建
            $save_path = $dir;
            do {
                $name = time() . rand(1, 1000000);
                $save_path = $dir . "/" . $name . $ext;
            } while (file_exists($save_path));
            // 生成文件
            file_put_contents($save_path, base64_decode($data), true);
            // 返回
            $ret = array('msg' => "/" . $save_path, 'code' => '1');
        }
        echo json_encode($ret);
        exit;
    }

    public function setRandomQuestion()
    {
        $questionnaire_id = I("post.questionnaire_id", "", "");
        $has_random = I("post.has_random", "", "");
        $from = I("post.from", "", "");
        $to = I("post.to", "", "");
        $count = I("post.count", "", "");
        $updated = 0;
        if ($has_random == QuestionnaireModel::RANDOM_OFF) {
            $data = array('has_random' => QuestionnaireModel::RANDOM_OFF, 'random_condition1' => '', 'random_condition2' => '', 'random_condition3' => '');
            $updated = M("questionnaire")->where(['id' => $questionnaire_id])->save($data);
        } else {
            $data = array('has_random' => QuestionnaireModel::RANDOM_ON, 'random_condition1' => '', 'random_condition2' => '', 'random_condition3' => '');
            $from_arr = explode("|", $from);
            $to_arr = explode("|", $to);
            $count_arr = explode("|", $count);
            if (!empty($from_arr)) {
                foreach ($from_arr as $key => $value) {
                    if ($value != '') {
                        $random_condition = array("from" => $value, "to" => $to_arr[$key], "count" => $count_arr[$key]);
                        switch ($key) {
                            case 0:
                                $data['random_condition1'] = serialize($random_condition);
                                break;
                            case 1:
                                $data['random_condition2'] = serialize($random_condition);
                                break;
                            case 2:
                                $data['random_condition3'] = serialize($random_condition);
                                break;
                            default:
                                break;
                        }
                    }
                }
                $updated = M("questionnaire")->where(['id' => $questionnaire_id])->save($data);
            }
        }
        if ($updated) {
            $this->ajaxReturn(array('status' => 1, 'msg' => '保存成功'));
        } else {
            $this->ajaxReturn(array('status' => 0, 'msg' => '保存失败'));
        }
    }

    public function uploadBackgroundImage()
    {
        $questionnaire_id = I("post.questionnaire_id", "", "");
        $background_question = I("post.background_question", "", "") ? I("post.background_question", "", "") : '/Public/images/questionnaire/question_background.jpg';
        $updated = M("questionnaire")->where(['id' => $questionnaire_id])->save(['background_question' => $background_question]);
        if ($updated) {
            $this->ajaxReturn(array('status' => 1, 'msg' => '保存成功'));
        } else {
            $this->ajaxReturn(array('status' => 0, 'msg' => '保存失败'));
        }
    }

    public function updateSort()
    {
        $id1 = I("post.id1", "", "");
        $id2 = I("post.id2", "", "");
        $question1 = M("questionnaire_questions")->where(['id' => $id1])->field("displayorder")->find();
        $question2 = M("questionnaire_questions")->where(['id' => $id2])->field("displayorder")->find();
        $updated1 = M("questionnaire_questions")->where(['id' => $id1])->save(['displayorder' => $question2['displayorder']]);
        $updated2 = M("questionnaire_questions")->where(['id' => $id2])->save(['displayorder' => $question1['displayorder']]);
        if ($updated1 && $updated2) {
            $this->ajaxReturn(array('status' => 1, 'msg' => '保存成功', 'displayorder1' => $question2['displayorder'], 'displayorder2' => $question1['displayorder']));
        } else {
            $this->ajaxReturn(array('status' => 0, 'msg' => '保存失败'));
        }
    }

    public function ending()
    {
        $questionnaire_id = I("get.questionnaire_id", -1, "");
        $questionnaire = M("questionnaire")->where(['id' => $questionnaire_id])->field("id,ending_play,ending_share,ending_background,ending_jump,ending_jumplink,ending_qrcode,has_qrcode")->find();

        $questionnaire_ending = M("questionnaire_ending")->where(['questionnaire_id' => $questionnaire_id, 'status' => QuestionnaireModel::ENDING_ACTIVE])->field("title,info,lower_limit,upper_limit,activity_title,activity_url,ending_image")->select();
        $this->assign("questionnaire", $questionnaire);
        $this->assign("questionnaire_ending", $questionnaire_ending);
        $this->display();
    }

    public function endingUpdate()
    {
        $questionnaire_id = I("post.questionnaire_id", "", "");
        $ending_data1 = array(
            'ending_play' => I("post.ending_play", "", "") ? I("post.ending_play", "", "") : '/Public/images/questionnaire/ending_play.jpg',
            'ending_share' => I("post.ending_share", "", "") ? I("post.ending_share", "", "") : '/Public/images/questionnaire/ending_share.jpg',
            'ending_background' => I("post.ending_background", "", "") ? I("post.ending_background", "", "") : '/Public/images/questionnaire/ending_background.jpg',
            'ending_jump' => I("post.ending_jump", "", ""),
            'ending_jumplink' => I("post.ending_jumplink", "", ""),
            'ending_qrcode' => I("post.ending_qrcode", "", "") ? I("post.ending_qrcode", "", "") : '/Public/images/home/zbgyEcode.jpg',
            'has_qrcode' => I("post.has_qrcode", "", "")
        );
        $updated1 = M("questionnaire")->where(['id' => $questionnaire_id])->save($ending_data1);

        $ending_title = I("post.title", "", "");
        $ending_info = I("post.info", "", "");
        $lower_limit = I("post.lower_limit", "", "");
        $upper_limit = I("post.upper_limit", "", "");
        $activity_title = I("post.activity_title", "", "");
        $activity_url = I("post.activity_url", "", "");
//        $activity_image = I("post.activity_image", "", "");
        $ending_image = I("post.ending_image", "", "");
        $updated2 = 0;
        if (!empty($ending_info)) {
            foreach ($ending_info as $key => $value) {
                if ($value || $key == 0) {
                    $ending_data2[] = array(
                        'questionnaire_id' => $questionnaire_id,
                        'title' => $ending_title[$key],
                        'info' => $value,
                        'lower_limit' => $lower_limit[$key],
                        'upper_limit' => $upper_limit[$key],
                        'activity_title' => $activity_title[$key],
                        'activity_url' => $activity_url[$key],
//                        'activity_image' => $activity_image[$key],
                        'ending_image' => $ending_image[$key] ? $ending_image[$key] : '/Public/images/questionnaire/reward.gif'
                    );
                }
            }
            M("questionnaire_ending")->where(['questionnaire_id' => $questionnaire_id])->save(['status' => QuestionnaireModel::ENDING_DELETE]);
            if (!empty($ending_data2)) {
                $updated2 = M("questionnaire_ending")->addAll($ending_data2);
            } else {
                $updated2 = 0;
            }
        }
        if ($updated1 > 0 || $updated2 > 0) {
            $this->success("保存成功", "/User/Questionnaire/ending/questionnaire_id/" . $questionnaire_id);
        } else {
            $this->error("保存失败", "/User/Questionnaire/ending");
        }
    }

    public function statistics()
    {
        $id = I("get.id", -1, "");
        $condition['questionnaire_id'] = $id;
        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        //加上缓存数据
        $cache = S('questionnaire_puv_' . $id);
        if ($cache) {
            $latest_statistics = M("questionnaire_statistics")->where(['questionnaire_id' => $id, 'date' => $cache['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->find();
            if (!empty($latest_statistics)) {
                M("questionnaire_statistics")->where(['questionnaire_id' => $id, 'date' => $cache['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE])
                    ->save(['page_view' => $cache['pv'], 'reserve' => $cache['uv']]);
            } else {
                $data = array(
                    'questionnaire_id' => $id,
                    'date' => $cache['date'],
                    'page_view' => $cache['pv'],
                    'reserve' => $cache['uv']
                );
                M("questionnaire_statistics")->add($data);
            }
        }

        $today = date("Y-m-d", time());
        $day_complete = M("questionnaire_fans")->where(['questionnaire_id' => $id, 'date' => $today, 'status' => QuestionnaireModel::STATISTICS_ACTIVE, 'enddate' => array('NEQ', 'NULL')])->count();
        $total_complete = M("questionnaire_fans")->where(['questionnaire_id' => $id, 'status' => QuestionnaireModel::STATISTICS_ACTIVE, 'enddate' => array('NEQ', 'NULL')])->count();
        $duration = M("questionnaire_fans")->where(['questionnaire_id' => $id, 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->sum("duration");
        $total_participate = M("questionnaire_fans")->where(['questionnaire_id' => $id, 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->count();
        if ($total_complete) {
            $duration = $duration / $total_participate;
            $average_duration = $duration <= 3600 ? date("i:s", $duration) : date("H:i:s", $duration);
            $rate = number_format($total_complete / $total_participate * 100, 2) . "%";
        } else {
            $average_duration = "-";
            $rate = "-";
        }
        $page_view = M("questionnaire_statistics")->where(['questionnaire_id' => $id, 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->sum("page_view");
        $uv_count = M("questionnaire_statistics")->where(['questionnaire_id' => $id, 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->sum("reserve");

        $count = M("questionnaire_statistics")->where($condition)->count();
        $offset = $count >= 15 ? $count - 15 : 0;
        $list = M("questionnaire_statistics")->where($condition)->limit($offset, 15)->order('id asc')->field('date,page_view,reserve as uv')->select();
        if (!empty($list)) {
            foreach ($list as &$value) {
                $value['date'] = date("m/d", strtotime($value['date']));
            }
            $list = json_encode($list);
        }
        $this->assign("id", $id);
        $this->assign("total_complete", $total_complete);
        $this->assign("day_complete", $day_complete);
        $this->assign("average_duration", $average_duration);
        $this->assign("page_view", $page_view);
        $this->assign("uv_count", $uv_count);
        $this->assign("rate", $rate);
        $this->assign("list", $list);
        $this->display("statistics_graph");
    }

    public function statisticsDate()
    {
        $id = I("get.id", -1, "");
        $condition['questionnaire_id'] = $id;
        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        $count = M("questionnaire_statistics")->where($condition)->count();

        $page = new Page($count, 15);
        $show = $page->show();
        $this->assign("page", $show);
        $list = M("questionnaire_statistics")->where($condition)->limit($page->firstRow . ',' . $page->listRows)->order('id desc')->field('id,date,page_view,reserve')->select();
        $questionnaire_fans = M("questionnaire_fans");
        if (!empty($list)) {
            foreach ($list as &$value) {
                $day_complete = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => $value['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE, 'enddate' => array('NEQ', 'NULL')])->count();
                $total_complete = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => array('elt', $value['date']), 'status' => QuestionnaireModel::STATISTICS_ACTIVE, 'enddate' => array('NEQ', 'NULL')])->count();
                $value['day_complete'] = $day_complete;
                $value['total_complete'] = $total_complete;
                $duration = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => $value['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->sum("duration");
                $day_participate = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => $value['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->count();
                if ($day_complete) {
                    $duration = $duration / $day_complete;
                    $value['average_duration'] = $duration <= 3600 ? date("i:s", $duration) : date("H:i:s", $duration);
                    $value['rate'] = number_format($day_complete / $day_participate * 100, 2) . "%";
                } else {
                    $value['average_duration'] = "-";
                    $value['rate'] = "-";
                }
            }
        }
        $this->assign("id", $id);
        $this->assign("list", $list);
        $this->display("statistics_date");
    }

    public function deleteDates()
    {
        $ids = I("get.ids", "", "");
        if (!empty($ids)) {
            $ids = explode('|', $ids);
        }
        $condition['id'] = array('IN', $ids);
        $updated = M("questionnaire_statistics")->where($condition)->save(array('status' => QuestionnaireModel::STATISTICS_DELETE));
        if ($updated) {
            $this->success("删除成功", "", true);
        } else {
            $this->error("删除失败", "", true);
        }
    }

    public function deleteDate()
    {
        $condition['id'] = I("get.id", "", "");
        $latest_statistics = M("questionnaire_statistics")->where(['id' => $condition['id'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->find();
        $cache = S('questionnaire_puv_' . $latest_statistics["questionnaire_id"]);
        if ($latest_statistics['date'] == $cache['date']) {
            S('questionnaire_puv_' . $latest_statistics["questionnaire_id"], null);
        }
        $updated = M("questionnaire_statistics")->where($condition)->save(array('status' => QuestionnaireModel::STATISTICS_DELETE));
        if ($updated) {
            $this->success("删除成功", "", true);
        } else {
            $this->error("删除失败", "", true);
        }
    }

    public function exportDate()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        if (empty($id)) {
            $this->redirect("/User/Questionnaire/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(10);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(20);
        $objActSheet->getColumnDimension('D')->setWidth(20);
        $objActSheet->getColumnDimension('E')->setWidth(20);
        $objActSheet->getColumnDimension('F')->setWidth(20);
        $objActSheet->getColumnDimension('G')->setWidth(20);
        $objActSheet->getColumnDimension('H')->setWidth(20);
        $objActSheet->setCellValue('A1', "编号");
        $objActSheet->setCellValue('B1', "时间");
        $objActSheet->setCellValue('C1', "新增完成量");
        $objActSheet->setCellValue('D1', "完成总量");
        $objActSheet->setCellValue('E1', "平均答题时间");
        $objActSheet->setCellValue('F1', "完成率");
        $objActSheet->setCellValue('G1', "PV");
        $objActSheet->setCellValue('H1', "UV");
        $condition['questionnaire_id'] = $id;
        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        $line = 2;
        $day_complete = 0;
        $questionnaire_fans = M("questionnaire_fans");
        $list = M("questionnaire_statistics")->where($condition)->order('id desc')->select();
        if (!empty($list)) {
            foreach ($list as $value) {
                $day_complete = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => $value['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE, 'enddate' => array('NEQ', 'NULL')])->count();
                $total_complete = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => array('elt', $value['date']), 'status' => QuestionnaireModel::STATISTICS_ACTIVE, 'enddate' => array('NEQ', 'NULL')])->count();
                $value['day_complete'] = $day_complete;
                $value['total_complete'] = $total_complete;
                $duration = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => $value['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->sum("duration");
                $day_participate = $questionnaire_fans->where(['questionnaire_id' => $id, 'date' => $value['date'], 'status' => QuestionnaireModel::STATISTICS_ACTIVE])->count();
                if ($day_complete) {
                    $duration = $duration / $day_complete;
                    $value['average_duration'] = $duration <= 3600 ? date("i:s", $duration) : date("H:i:s", $duration);
                    $value['rate'] = number_format($day_complete / $day_participate * 100, 2) . "%";
                } else {
                    $value['average_duration'] = "-";
                    $value['rate'] = "-";
                }
                $objActSheet->setCellValue('A' . $line, $value['id']);
                $objActSheet->setCellValue('B' . $line, $value['date']);
                $objActSheet->setCellValue('C' . $line, $value['day_complete']);
                $objActSheet->setCellValue('D' . $line, $value['total_complete']);
                $objActSheet->setCellValue('E' . $line, $value['average_duration']);
                $objActSheet->setCellValue('F' . $line, $value['rate']);
                $objActSheet->setCellValue('G' . $line, $value['page_view']);
                $objActSheet->setCellValue('H' . $line, $value['reserve']);
                $objActSheet->getRowDimension($line)->setRowHeight(20);
                $line++;
            }
        }
        $fileName = '最新数据' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }

    public function statisticsUser()
    {
        $id = I("get.id", -1, "");
        $condition['questionnaire_id'] = $id;
        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        $list = array();
        $params = I("get.", "", "");
        if (!empty($params['question3']) && !empty($params['value3'])) {//---有筛选条件--
            $cond_fans_ans['question_id'] = $params['question3'];
            $cond_fans_ans['option_id'] = $params['value3'];
            $count = M("questionnaire_fans_ans")->where($cond_fans_ans)->count();
            $page = new Page($count, 15);
            $show = $page->show();
            $this->assign("page", $show);
            $fans_list = M("questionnaire_fans_ans")->where($cond_fans_ans)->limit($page->firstRow . ',' . $page->listRows)
                ->order('ans_id desc')->field('ans_id,fans_id,question_id,option_id')->select();
            $fans_id_list = array();
            foreach ($fans_list as $fans) {
                $fans_id_list[] = $fans['fans_id'];
            }
            if (!empty($fans_id_list)) {
                $cond_fans['id'] = array("IN", $fans_id_list);
                $cond_fans['status'] = QuestionnaireModel::ANSWER_ACTIVE;
                $list = M("questionnaire_fans")->where($cond_fans)->select();
                if(!empty($list)) {
                    foreach ($list as &$value) {
                        $nickname = json_decode($value['nickname']);
                        if($nickname) $value['nickname'] = $nickname;
                    }
                }
            }
        } else {//---无筛选条件--
            $count = M("questionnaire_fans")->where($condition)->count();
            $page = new Page($count, 15);
            $show = $page->show();
            $this->assign("page", $show);
            $list = M("questionnaire_fans")->where($condition)->limit($page->firstRow . ',' . $page->listRows)
                ->order('id desc')->field('id,openid,startdate,enddate,duration,scores,reserve,nickname')->select();
            if (!empty($list)) {
                foreach ($list as &$value) {
                    $nickname = json_decode($value['nickname']);
                    if($nickname) $value['nickname'] = $nickname;
                    if ($value['duration'] == 0) {
                        $value['duration'] = "-";
                    } else {
                        $value['duration'] = $value['duration'] <= 3600 ? date("i:s", $value['duration']) : date("H:i:s", $value['duration']);
                    }
                }
            }
        }
        $this->assign("id", $id);
        $this->assign("list", $list);
        $question_arr = M("questionnaire_questions")->where($condition)->select();
        $this->assign("question_list", $question_arr);
        $this->display("statistics_user");
    }

    public function statisticsOption()
    {
        $id = I("get.id", -1, "");
        $condition['questionnaire_id'] = $id;
        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        $count = M("questionnaire_questions")->where($condition)->count();

        $page = new Page($count, 15);
        $show = $page->show();
        $this->assign("page", $show);
        $list = M("questionnaire_questions")->where($condition)->limit($page->firstRow . ',' . $page->listRows)
            ->order('displayorder asc')->field('id,title')->select();

        $option_arr = array();
        if (!empty($list)) {
            $question_arr = array();
            foreach ($list as $question) {
                $question_arr[] = $question['id'];
            }
            $cond_option['status'] = QuestionnaireModel::ANSWER_ACTIVE;
            $cond_option['question_id'] = array("IN", $question_arr);
            $option_list = M("questionnaire_questions_options")->where($cond_option)->select();

            foreach ($option_list as $option) {
                $option_arr[$option['question_id']][] = $option;
            }
        }
        $this->assign("id", $id);
        $this->assign("list", $list);
        $this->assign("option_arr", $option_arr);
        $this->display("statistics_option");
    }

    public function exportOption()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        if (empty($id)) {
            $this->redirect("/User/Questionnaire/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(20);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(10);
        $objActSheet->getColumnDimension('D')->setWidth(10);
        $objActSheet->setCellValue('A1', "题目");
        $objActSheet->setCellValue('B1', "选项");
        $objActSheet->setCellValue('C1', "选择次数");
        $objActSheet->setCellValue('D1', "百分比");
        $condition['questionnaire_id'] = $id;
        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        $line = 2;
        $list = M("questionnaire_questions")->where($condition)->order('displayorder asc')->select();
        if (!empty($list)) {
            $question_arr = array();
            foreach ($list as $question) {
                $question_arr[] = $question['id'];
            }
            $cond_option['status'] = QuestionnaireModel::ANSWER_ACTIVE;
            $cond_option['question_id'] = array("IN", $question_arr);
            $option_list = M("questionnaire_questions_options")->where($cond_option)->select();

            foreach ($option_list as $option) {
                $option_arr[$option['question_id']][] = $option;
            }
        }
        foreach ($list as $question) {
            $objActSheet->setCellValue('A' . $line, $question['title']);
            if (array_key_exists($question['id'], $option_arr)) {
                $objActSheet->setCellValue('B' . $line, $option_arr[$question['id']][0]['title']);
                $objActSheet->setCellValue('C' . $line, $option_arr[$question['id']][0]['count']);
                $count = 0;
                foreach ($option_arr[$question['id']] as $key => $option){
                    $count += $option['count'];
                }
                if ($count == 0) {
                    $objActSheet->setCellValue('D' . $line, 0);
                } else {
                    $objActSheet->setCellValue('D' . $line, round($option_arr[$question['id']][0]['count'] / $count, 2));
                }
                foreach ($option_arr[$question['id']] as $key => $option) {
                    if ($key != 0) {
                        $line++;
                        $objActSheet->setCellValue('A' . $line, "");
                        $objActSheet->setCellValue('B' . $line, $option['title']);
                        $objActSheet->setCellValue('C' . $line, $option['count']);
                        if ($count == 0) {
                            $objActSheet->setCellValue('D' . $line, 0);
                        } else {
                            $objActSheet->setCellValue('D' . $line, round($option['count'] / $count, 2));
                        }
                    }
                }
            } else {

            }
            $line++;
        }
        $fileName = '选题统计' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }

    public function deleteUsers()
    {
        $ids = I("get.ids", "", "");
        if (!empty($ids)) {
            $ids = explode('|', $ids);
        }
        $condition['id'] = array('IN', $ids);
        $updated = M("questionnaire_fans")->where($condition)->save(array('status' => QuestionnaireModel::STATISTICS_DELETE));
        if ($updated) {
            $this->success("删除成功", "", true);
        } else {
            $this->error("删除失败", "", true);
        }
    }

    public function deleteUser()
    {
        $condition['id'] = I("get.id", "", "");
        $updated = M("questionnaire_fans")->where($condition)->save(array('status' => QuestionnaireModel::STATISTICS_DELETE));
        if ($updated) {
            $this->success("删除成功", "", true);
        } else {
            $this->error("删除失败", "", true);
        }
    }

    public function exportUser()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        $question3 = I("get.question3", "", "");
        $value3 = I("get.value3", "", "");
        if (empty($id)) {
            $this->redirect("/User/Questionnaire/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(10);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(30);
        $objActSheet->getColumnDimension('D')->setWidth(30);
        $objActSheet->getColumnDimension('E')->setWidth(10);
        $objActSheet->getColumnDimension('F')->setWidth(30);
        $objActSheet->getColumnDimension('G')->setWidth(30);
        $objActSheet->getColumnDimension('H')->setWidth(30);
        $objActSheet->setCellValue('A1', "编号");
        $objActSheet->setCellValue('B1', "用户");
        $objActSheet->setCellValue('C1', "开始答题");
        $objActSheet->setCellValue('D1', "答题时长");
        $objActSheet->setCellValue('E1', "得分");
        $objActSheet->setCellValue('F1', "手机型号");
        $objActSheet->setCellValue('G1', "用户头像");
        $objActSheet->setCellValue('H1', "用户昵称");
        $condition['questionnaire_id'] = $id;
        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        $line = 2;
        $count = 0;
        if (!empty($question3) && !empty($value3)) {
            $cond_fans_ans['question_id'] = $question3;
            $cond_fans_ans['option_id'] = $value3;
            $count = M("questionnaire_fans_ans")->where($cond_fans_ans)->count();
        } else {
            $count = M("questionnaire_fans")->where($condition)->count();
        }
        $number = $count / 100;
        for ($i = 0; $i <= $number; $i++) {
            $list = array();
            if (!empty($question3) && !empty($value3)) {
                $cond_fans_ans['question_id'] = $question3;
                $cond_fans_ans['option_id'] = $value3;
                $fans_list = M("questionnaire_fans_ans")->where($cond_fans_ans)->order('ans_id desc')->select();
                $fans_id_list = [];
                foreach ($fans_list as $fans) {
                    $fans_id_list[] = $fans['fans_id'];
                }

                if (!empty($fans_id_list)) {
                    $cond_fans['id'] = array("IN", $fans_id_list);
                }
                $list = M("questionnaire_fans")->where($cond_fans)->order("id desc")->select();
            } else {
                $list = M("questionnaire_fans")->where($condition)->limit($i * 100, 100)->order('id desc')->select();
            }
            if (!empty($list)) {
                foreach ($list as $value) {
                    if ($value['duration'] == 0) {
                        $value['duration'] = "-";
                    } else {
                        $value['duration'] = $value['duration'] <= 3600 ? date("i:s", $value['duration']) : date("H:i:s", $value['duration']);
                    }
                    $objActSheet->setCellValue('A' . $line, $value['id']);
                    $objActSheet->setCellValue('B' . $line, $value['openid']);
                    $objActSheet->setCellValue('C' . $line, $value['startdate']);
                    $objActSheet->setCellValue('D' . $line, $value['duration']);
                    $objActSheet->setCellValue('E' . $line, $value['scores']);
                    $objActSheet->setCellValue('F' . $line, $value['phone_type']);
                    $img = @imagecreatefromjpeg(C("SITE_URL") . $value['reserve']);
                    if ($img) {
                        $objDrawing = new \PHPExcel_Worksheet_MemoryDrawing();
                        $objDrawing->setImageResource($img);
                        $objDrawing->setHeight(120);
                        $objDrawing->setWidth(120);
                        $objDrawing->setCoordinates('G' . $line);
                        $objDrawing->setOffsetX(10);
                        $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT);
                        $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                        $objDrawing->setWorksheet($objActSheet);
                    } else {
                        $objActSheet->setCellValue('G' . $line, '');
                    }
                    $nickname = json_decode($value['nickname']);
                    if($nickname) $value['nickname'] = $nickname;
                    $objActSheet->setCellValue('H' . $line, $value['nickname']);
                    $objActSheet->getRowDimension($line)->setRowHeight(120);
                    $line++;
                }
            }
        }

        $fileName = '用户行为' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }

    public function exportDetail()
    {
        set_time_limit(0);
        $id = I("get.id", "", "");
        if (empty($id)) {
            $this->redirect("/User/Questionnaire/index");
        }
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(10);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->getColumnDimension('C')->setWidth(30);
        $objActSheet->getColumnDimension('D')->setWidth(30);
        $objActSheet->getColumnDimension('E')->setWidth(10);
        $objActSheet->getColumnDimension('F')->setWidth(30);
        $objActSheet->getColumnDimension('G')->setWidth(30);
        $objActSheet->getColumnDimension('H')->setWidth(30);
        $objActSheet->setCellValue('A1', "编号");
        $objActSheet->setCellValue('B1', "用户");
        $objActSheet->setCellValue('C1', "开始答题");
        $objActSheet->setCellValue('D1', "答题时长");
        $objActSheet->setCellValue('E1', "得分");
        $objActSheet->setCellValue('F1', "手机型号");
        $objActSheet->setCellValue('G1', "用户头像");
        $objActSheet->setCellValue('H1', "用户昵称");
        $condition['id'] = $id;
//        $condition['status'] = QuestionnaireModel::STATISTICS_ACTIVE;
        $line = 2;
        $fans = M("questionnaire_fans")->where($condition)->find();
        if (!empty($fans)) {
            if ($fans['duration'] == 0) {
                $fans['duration'] = "-";
            } else {
                $fans['duration'] = $fans['duration'] <= 3600 ? date("i:s", $fans['duration']) : date("H:i:s", $fans['duration']);
            }
            $objActSheet->setCellValue('A' . $line, $fans['id']);
            $objActSheet->setCellValue('B' . $line, $fans['openid']);
            $objActSheet->setCellValue('C' . $line, $fans['startdate']);
            $objActSheet->setCellValue('D' . $line, $fans['duration']);
            $objActSheet->setCellValue('E' . $line, $fans['scores']);
            $objActSheet->setCellValue('F' . $line, $fans['phone_type']);
            $img = @imagecreatefromjpeg(C("SITE_URL") . $fans['reserve']);
            if ($img) {
                $objDrawing = new \PHPExcel_Worksheet_MemoryDrawing();
                $objDrawing->setImageResource($img);
                $objDrawing->setHeight(120);
                $objDrawing->setWidth(120);
                $objDrawing->setCoordinates('G' . $line);
                $objDrawing->setOffsetX(10);
                $objDrawing->setRenderingFunction(\PHPExcel_Worksheet_MemoryDrawing::RENDERING_DEFAULT);
                $objDrawing->setMimeType(\PHPExcel_Worksheet_MemoryDrawing::MIMETYPE_DEFAULT);
                $objDrawing->setWorksheet($objActSheet);
            } else {
                $objActSheet->setCellValue('G' . $line, '');
            }
            $nickname = json_decode($fans['nickname']);
            if($nickname) $fans['nickname'] = $nickname;
            $objActSheet->setCellValue('H' . $line, $fans['nickname']);
            $objActSheet->getRowDimension($line)->setRowHeight(120);
            $line++;
            if (!empty($fans['answer'])) {
                $questions_options = explode("|", $fans['answer']);
                $questions = array();
                if (!empty($questions_options)) {
                    foreach ($questions_options as $value1) {
                        $item = explode(",", $value1);
                        $questions[$item[0]] = $item[1];
                    }
                    if (!empty($questions)) {
                        $objActSheet->mergeCells('A' . $line . ':D' . $line);
                        $objActSheet->setCellValue('A' . $line, "题目:");
                        $objActSheet->mergeCells('E' . $line . ':H' . $line);
                        $objActSheet->setCellValue('E' . $line, "选择结果:");
                        $line++;
                        $list = M("questionnaire_questions_options")->where(["question_id" => array("in", array_keys($questions)), "status" => QuestionnaireModel::ANSWER_ACTIVE])->getField("id,title,score,is_extra");
                        $questions_list = M("questionnaire_questions")->where(["question_id" => array("in", array_keys($questions))])->getField("id,title");
                        $extra_list = M("questionnaire_fans_ans")->where(["fans_id" => $fans['id'], "question_id" => array("in", array_keys($questions))])->getField("option_id,extra_answer");
                        foreach ($questions as $question_id => $options) {
                            $objActSheet->mergeCells('A' . $line . ':D' . $line);
                            if (array_key_exists($question_id, $questions_list)) {
                                $objActSheet->setCellValue('A' . $line, $questions_list[$question_id]);
                            } else {
                                $objActSheet->setCellValue('A' . $line, '');
                            }
                            $objActSheet->mergeCells('E' . $line . ':H' . $line);
                            if (strpos($options, ";")) {
                                $option_arr = explode(";", $options);
                                $cellvalue_e = '';
                                foreach ($option_arr as $option) {
                                    if (array_key_exists($option, $list)) {
                                        if ($list[$option]['is_extra'] == QuestionnaireModel::EXTRA_ON) {
                                            $cellvalue_e .= $list[$option]['title'] . "(" . $list[$option]['score'] . "):" . $extra_list[$option] . "\r\n";
                                        } else {
                                            $cellvalue_e .= $list[$option]['title'] . "(" . $list[$option]['score'] . ")" . "\r\n";
                                        }
                                    }
                                }
                                $objActSheet->setCellValue('E' . $line, $cellvalue_e);
                            } else {
                                if (array_key_exists($options, $list)) {
                                    if ($list[$options]['is_extra'] == QuestionnaireModel::EXTRA_ON) {
                                        $objActSheet->setCellValue('E' . $line, $list[$options]['title'] . "(" . $list[$options]['score'] . "):" . $extra_list[$options]);
                                    } else {
                                        $objActSheet->setCellValue('E' . $line, $list[$options]['title'] . "(" . $list[$options]['score'] . ")");
                                    }
                                }
                            }
                            $line++;
                        }
                    }
                }
            }
        }
        $user_name = empty($fans['nickname']) ? '' : $fans['nickname'];
        $fileName = '用户行为' . $user_name . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }

    public function clearOption()
    {
        $where["questionnaire_id"] = I("get.id", -1);
        $where["status"] = QuestionnaireModel::QUESTION_ACTIVE;
        $questions = M("questionnaire_questions")->where($where)->field("id")->select();
        $question_ids = array();
        if (!empty($questions)) {
            foreach ($questions as $value) {
                $question_ids[] = $value["id"];
            }
        }
        $where_option["question_id"] = array("in", $question_ids);
        $where_option["status"] = QuestionnaireModel::ANSWER_ACTIVE;
        $updated = M("questionnaire_questions_options")->where($where_option)->save(array("count" => 0));
        if ($updated !== false) {
            $this->success("清空成功", "", true);
        } else {
            $this->error("清空失败", "", true);
        }
    }

    //---获取选项--
    public function getOption()
    {
        $id = I("get.id", 0, "");
        $res = array();
        if (empty($id)) {
            $this->ajaxReturn($res);
        }
        $cond['question_id'] = $id;
        $cond['status'] = QuestionnaireModel::ANSWER_ACTIVE;
        $option_arr = M("questionnaire_questions_options")->where($cond)->select();
        $this->ajaxReturn($option_arr);
    }
}

?>